package com.huiquan.symptom.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.ModelAndView;

import com.huiquan.analysis.domain.User;
import com.huiquan.framework.base.BaseService;
import com.huiquan.framework.base.ReturnData;
import com.huiquan.framework.constant.BaseContants;
import com.huiquan.framework.utils.GetListUtil;
import com.huiquan.framework.utils.ReturnUtil;
import com.huiquan.symptom.dao.SymptomDao;
import com.huiquan.symptom.domain.Symptom;
import com.huiquan.symptom.domain.SymptomReveal;

@Service
public class SymptomService extends BaseService {

	@Autowired
	private SymptomDao symptomDao;

	public ModelAndView list(Integer start, String keyword, String exactSearchFlag, String tabid,
			String countPerPageStr) {

		boolean exactFlag = exactSearchFlag != null && exactSearchFlag.equals("1");

		Map<String, Object> param = new HashMap<>();
		if (keyword != null && !keyword.isEmpty()) {
			param.put("keyword", exactFlag ? keyword : "%" + keyword + "%");
		}
		if (StringUtils.equalsIgnoreCase(tabid, "29_1")) {
			param.put("unchecked", "1");
		} else if (StringUtils.equalsIgnoreCase(tabid, "29_2")) { // 黑名单
			param.put("blacklistFlag", BaseContants.FLAG_YES);
			param.put("orderStr", "gmt_modified desc");
		} else if (StringUtils.equalsIgnoreCase(tabid, "29_3")) { // 已校验白名单
			param.put("checked", "1");
			param.put("blacklistFlag", BaseContants.FLAG_NO);
			param.put("orderStr", "gmt_modified desc");
		}
		int totalSize = symptomDao.retrieveSize(param);

		Map<String, Integer> pageNo = new HashMap<>();
		if (countPerPageStr != null && !countPerPageStr.isEmpty()) {
			int countPerPage = Integer.parseInt(countPerPageStr);
			pageNo = GetListUtil.getPageNoParam(totalSize, start + "", countPerPage);
			param.put("countPerPage", countPerPage);
		} else {
			pageNo = GetListUtil.getPageNoParam(totalSize, start + "");
		}
		int endPage = pageNo.get("endPage");
		start = pageNo.get("start");
		int startIndex = pageNo.get("startIndex");

		List<Symptom> list = new ArrayList<>();

		if (startIndex < totalSize) {
			param.put("startIndex", startIndex);
			list = symptomDao.retrieveList(param);
		}

		Map<String, String> showSearch = new LinkedHashMap<>();
		showSearch.put("keyword", "症状");
		Map<String, String> searchMap = new HashMap<>();
		searchMap.put("keyword", keyword);
		Map<String, Object> map = GetListUtil.getReturnMap2(totalSize, start, startIndex, endPage, list, searchMap);
		map.put("showSearch", showSearch);
		map.put("showSearchValue", searchMap);
		map.put("exactSearchFlag", exactSearchFlag);
		return new ModelAndView("symptom/index", map);
	}

	/**
	 * 得到展现词列表
	 * 
	 * @param start
	 * @param keyword
	 * @param exactSearchFlag
	 * @param status
	 * @return
	 */
	public Map<String, Object> revealList(Integer start, String keyword, String exactSearchFlag, String status,
			String tabid, String countPerPageStr) {
		boolean exactFlag = exactSearchFlag != null && exactSearchFlag.equals("1");

		Map<String, Object> param = new HashMap<>();
		if (StringUtils.isNotEmpty(keyword)) {
			param.put("keyword", exactFlag ? keyword : "%" + keyword + "%");
		}
		if (StringUtils.isNotEmpty(status)) {
			param.put("status", status);
		}
		int totalSize = symptomDao.selectRevealSize(param);

		Map<String, Integer> pageNo = new HashMap<>();
		if (countPerPageStr != null && !countPerPageStr.isEmpty()) {
			int countPerPage = Integer.parseInt(countPerPageStr);
			pageNo = GetListUtil.getPageNoParam(totalSize, start + "", countPerPage);
			param.put("countPerPage", countPerPage);
		} else {
			pageNo = GetListUtil.getPageNoParam(totalSize, start + "");
		}
		int endPage = pageNo.get("endPage");
		start = pageNo.get("start");
		int startIndex = pageNo.get("startIndex");
		List<SymptomReveal> list = new ArrayList<>();
		if (startIndex < totalSize) {
			param.put("startIndex", startIndex);
			list = symptomDao.selectRevealList(param);
			for (SymptomReveal reveal : list) {
				splitSynonymInReveal(reveal);
			}
		}
		Map<String, String> showSearch = new LinkedHashMap<>();
		showSearch.put("keyword", "症状");
		Map<String, String> searchMap = new HashMap<>();
		searchMap.put("keyword", keyword);
		searchMap.put("status", status);
		searchMap.put("tabid", tabid);

		Map<String, Object> map = GetListUtil.getReturnMap2(totalSize, start, startIndex, endPage, list, searchMap);
		map.put("showSearch", showSearch);
		map.put("showSearchValue", searchMap);
		map.put("exactSearchFlag", exactSearchFlag);
		return map;
	}

	/**
	 * 将reveal中的同义词拆开
	 * 
	 * @param reveal
	 */
	private void splitSynonymInReveal(SymptomReveal reveal) {
		if (StringUtils.isNotEmpty(reveal.getSynonym())) {
			String[] synonyms;
			synonyms = reveal.getSynonym().split("\t");
			if (synonyms.length > 0) {
				reveal.setSynonym1(synonyms[0]);
			}
			if (synonyms.length > 1) {
				reveal.setSynonym2(synonyms[1]);
			}
			if (synonyms.length > 2) {
				reveal.setSynonym3(synonyms[2]);
			}
		}
	}

	public ModelAndView preEdit(String keyword, Integer start, String id, User user, Integer status) {
		Map<String, Object> map = new HashMap<>();
		map.put("start", start);
		map.put("keyword", keyword);
		map.put("status", status);

		return new ModelAndView("symptom/symptom_edit", map);
	}

	public ReturnData edit(Long id, String name, String list, String attribution, String blacklistFlag, User user) {
		Symptom symptom = new Symptom();
		symptom.setName(name);
		symptom.setAttribution(attribution);
		symptom.setBlacklistFlag(Integer.parseInt(blacklistFlag));
		symptom.setList(blacklistFlag);

		symptomDao.insert(symptom);
		return ReturnUtil.success();
	}

	public ModelAndView delete(Integer start, Long id, String keyword, String exactSearchFlag, String tabid,
			String countPerPageStr) {
		Symptom symptom = new Symptom();
		symptom.setId(id);
		symptomDao.delete(symptom);
		return list(start, keyword, exactSearchFlag, tabid, countPerPageStr);
	}

	public ModelAndView delBlacklist(Integer start, String id, String keyword, String exactSearchFlag, String tabid,
			User user, String countPerPageStr) {
		symptomDao.setBlacklistFlag(id, BaseContants.FLAG_NO, user.getUserId());
		return list(start, keyword, exactSearchFlag, tabid, countPerPageStr);
	}

	public ModelAndView addBlacklist(Integer start, String id, String keyword, String exactSearchFlag, String tabid,
			User user, String countPerPageStr) {
		symptomDao.setBlacklistFlag(id, BaseContants.FLAG_YES, user.getUserId());
		return list(start, keyword, exactSearchFlag, tabid, countPerPageStr);
	}

	/**
	 * 编辑一条展现词
	 * 
	 * @param user
	 * @param id
	 * @param symptomArray
	 * @param propArray
	 * @return
	 */
	public ReturnData editReveal(User user, int id, String symptomArray, String propArray) {
		String[] symptomArr = symptomArray.split(",");
		String[] propArr = propArray.split(",");
		if (symptomArr.length != propArr.length) {
			return ReturnUtil.customMessage("分词与属性不一致，请检查！");
		}
		SymptomReveal entity = symptomDao.selectRevealById(id);
		// 将更新前展现词、分词、属性插入到日志中记录
		Map<String, Object> revealLogParam = new HashMap<>();
		revealLogParam.put("rid", entity.getId());
		revealLogParam.put("symptomReveal", entity.getSymptomReveal());
		revealLogParam.put("symptomArray", entity.getSymptomArray());
		revealLogParam.put("propArray", entity.getPropArray());
		revealLogParam.put("modifierId", user.getUserId());
		revealLogParam.put("modifierName", user.getRealName());
		symptomDao.insertRevealLog(revealLogParam);
		// 得到新的展现词
		StringBuilder symptomReveal = new StringBuilder();
		for (int i = 0; i < symptomArr.length; i++) {
			symptomReveal.append(symptomArr[i]);
		}
		// 更新展现词
		Map<String, Object> revealParam = new HashMap<>();
		revealParam.put("id", id);
		revealParam.put("symptomReveal", symptomReveal.toString());
		revealParam.put("symptomArray", symptomArray);
		revealParam.put("propArray", propArray);
		revealParam.put("status", 1);
		revealParam.put("modifierId", user.getUserId());
		revealParam.put("modifierName", user.getRealName());
		symptomDao.updateReveal(revealParam);
		return ReturnUtil.success();
	}

	/**
	 * 更新一条展现词状态
	 * 
	 * @param user
	 * @param id
	 * @param revealStatus
	 * @return
	 */
	public ReturnData updateRevealStatus(User user, int id, int revealStatus) {
		if (revealStatus < 0 || revealStatus > 2) {
			return ReturnUtil.customMessage("展现词状态异常");
		}
		Map<String, Object> revealParam = new HashMap<>();
		revealParam.put("id", id);
		revealParam.put("status", revealStatus);
		revealParam.put("modifierId", user.getUserId());
		revealParam.put("modifierName", user.getRealName());
		symptomDao.updateReveal(revealParam);
		return ReturnUtil.success();
	}

	/**
	 * 根据选择的同义词改变展现词
	 * 
	 * @param user
	 * @param id
	 * @param symptomStd
	 * @param synonym
	 * @return
	 */
	public ReturnData changeRevealWithSynonym(User user, int id, String symptomStd, String synonym) {
		Map<String, String> synonymMap = symptomDao.selectSynonymWithStd(symptomStd, synonym);
		Map<String, Object> revealParam = new HashMap<>();
		revealParam.put("id", id);
		revealParam.put("status", 1);
		revealParam.put("modifierId", user.getUserId());
		revealParam.put("modifierName", user.getRealName());
		revealParam.put("symptomReveal", synonymMap.get("synonym"));
		revealParam.put("symptomArray", synonymMap.get("synonym_array"));
		revealParam.put("propArray", synonymMap.get("synonym_prop"));
		revealParam.put("num", synonymMap.get("synonym_num"));
		symptomDao.updateReveal(revealParam);
		return ReturnUtil.success();
	}
}
